from flask import request, jsonify, current_app
from flask_jwt_extended import get_jwt_identity, jwt_required

from app import db
from app.api.v1.admin import admin_blueprint
from app.models.agents import Agent
from app.models.cardRecord import CardRecord
from app.services.decorators import admin_required
from app.utils.site_config import (
    get_public_configs, set_config,
    delete_config, upload_config_file, SystemConfig
)


# 前端获取公开配置
@admin_blueprint.route('/configs/public', methods=['GET', 'OPTIONS'])
def get_public_configs_api():
    """获取所有公开的配置项，前端可直接访问"""
    return jsonify({
        'code': 0,
        'message': '获取成功',
        'data': get_public_configs()
    })


# 获取单个配置项
@admin_blueprint.route('/configs/get/<key>', methods=['GET', 'OPTIONS'])
@jwt_required(optional=True)
def get_config_by_key(key):
    """根据配置键名获取单个配置项
    
    参数：
        key: 配置键名
    
    返回：
        配置项详情，包括值、类型等
    """
    # 查询配置项
    config_item = SystemConfig.query.filter_by(config_key=key).first()

    if not config_item:
        return jsonify({
            'code': 1,
            'message': f'配置项 {key} 不存在'
        }), 404

    # 转换为字典并返回
    return jsonify({
        'code': 0,
        'message': '获取成功',
        'data': config_item.to_dict()
    })


# 管理员获取所有配置
@admin_blueprint.route('/configs', methods=['GET', 'OPTIONS'])
@jwt_required(optional=True)
@admin_required
def get_all_configs_api():
    """获取所有配置项，需要管理员权限"""
    # 获取配置分组
    group = request.args.get('group')

    all_configs = SystemConfig.query.order_by(SystemConfig.group_name, SystemConfig.config_key)
    if group:
        all_configs = all_configs.filter_by(group_name=group)

    return jsonify({
        'code': 0,
        'message': '获取成功',
        'data': [config.to_dict() for config in all_configs.all()]
    })


# 管理员更新配置
@admin_blueprint.route('/configs/<key>', methods=['PUT', 'OPTIONS'])
@jwt_required()
@admin_required
def update_config_api(key):
    """更新配置项，需要管理员权限"""
    data = request.json
    value = data.get('value')

    # 获取管理员ID
    admin_id = get_jwt_identity()

    success = set_config(
        key,
        value,
        value_type=data.get('type'),
        group=data.get('group'),
        description=data.get('description'),
        is_public=data.get('is_public'),
        admin_id=admin_id
    )

    if success:
        return jsonify({
            'code': 0,
            'message': '更新成功'
        })
    else:
        return jsonify({
            'code': 1,
            'message': '更新失败'
        }), 500


# 管理员删除配置
@admin_blueprint.route('/configs/<key>', methods=['DELETE', 'OPTIONS'])
@jwt_required(optional=True)
@admin_required
def delete_config_api(key):
    """删除配置项，需要管理员权限"""
    # 获取管理员ID
    admin_id = get_jwt_identity()

    success = delete_config(key, admin_id)

    if success:
        return jsonify({
            'code': 0,
            'message': '删除成功'
        })
    else:
        return jsonify({
            'code': 1,
            'message': '删除失败'
        }), 500


# 管理员上传配置文件
@admin_blueprint.route('/configs/upload/<key>', methods=['POST', 'OPTIONS'])
@jwt_required(optional=True)
@admin_required
def upload_config_file_api(key):
    """上传配置文件(如图片)，需要管理员权限"""
    if 'file' not in request.files:
        return jsonify({
            'code': 1,
            'message': '没有上传文件'
        }), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({
            'code': 1,
            'message': '没有选择文件'
        }), 400

    file_type = request.form.get('type', 'image')
    group = request.form.get('group', 'uploads')
    is_public = request.form.get('is_public', 'true').lower() in ('true', '1', 'yes')

    # 获取管理员ID
    admin_id = get_jwt_identity()

    success, result = upload_config_file(
        key,
        file,
        file_type=file_type,
        group=group,
        is_public=is_public,
        admin_id=admin_id
    )

    if success:
        return jsonify({
            'code': 0,
            'message': '上传成功',
            'data': {
                'url': result
            }
        })
    else:
        return jsonify({
            'code': 1,
            'message': result
        }), 500


# 小程序获取公开配置的无验证接口
@admin_blueprint.route('/mp/configs', methods=['GET', 'OPTIONS'])
def mp_get_configs():
    """小程序专用：获取所有公开配置（无JWT验证）"""
    try:
        return jsonify({
            'code': 0,
            'message': '获取成功',
            'data': get_public_configs()
        })
    except Exception as e:
        current_app.logger.error(f"获取小程序配置失败: {str(e)}")
        return jsonify({"code": -1, "message": f"获取配置失败: {str(e)}"}), 500


# 小程序根据键名获取配置项（不需要JWT验证）
@admin_blueprint.route('/configs/mp/get/<key>', methods=['GET', 'OPTIONS'])
def mp_get_config_by_key(key):
    """小程序专用：根据键名获取单个配置项（无JWT验证）"""
    try:
        # 查询配置项
        config_item = db.session.query(SystemConfig).filter_by(config_key=key).first()

        if not config_item:
            return jsonify({
                'code': 1,
                'message': f'配置项 {key} 不存在'
            }), 404

        # 转换为字典并返回
        return jsonify({
            'code': 0,
            'message': '获取成功',
            'data': config_item.to_dict()
        })
    except Exception as e:
        current_app.logger.error(f"获取配置项[{key}]失败: {str(e)}")
        return jsonify({"code": -1, "message": f"获取配置失败: {str(e)}"}), 500


@admin_blueprint.route('/configs/batch', methods=['PUT', 'OPTIONS'])
@admin_required
def batch_update_configs():
    """批量更新多个配置项"""
    data = request.json
    admin_id = get_jwt_identity() if get_jwt_identity() else None

    results = {}
    failed_keys = []

    for key, value in data.items():
        # 根据key获取现有配置的类型和分组
        config_item = SystemConfig.query.filter_by(config_key=key).first()
        if config_item:
            # 保持原有类型和分组
            success = set_config(
                key,
                value,
                value_type=config_item.value_type,
                group=config_item.group_name,
                description=config_item.description,
                is_public=config_item.is_public,
                admin_id=admin_id
            )
            if not success:
                failed_keys.append(key)
            results[key] = success
        else:
            # 如果配置不存在，尝试创建新配置
            success = set_config(
                key,
                value,
                admin_id=admin_id
            )
            if not success:
                failed_keys.append(key)
            results[key] = success

    if failed_keys:
        return jsonify({
            'code': 1,
            'message': f'部分配置更新失败: {", ".join(failed_keys)}',
            'data': results
        }), 500

    return jsonify({
        'code': 0,
        'message': '批量更新成功',
        'data': results
    })


@admin_blueprint.route('/configs/reset', methods=['POST', 'OPTIONS'])
@admin_required
def reset_configs():
    """重置所有配置到默认值"""
    admin_id = get_jwt_identity() if get_jwt_identity() else None

    try:
        # 获取默认配置
        default_configs = {
            'site_name': '学法减分题库管理系统',
            'site_logo': '/static/default_logo.png',
            'site_description': '学法减分题库管理系统',
            'contact_phone': '400-123-4567',
            'contact_email': 'admin@example.com',
            'alipay_enabled': 0,
            'wxpay_enabled': 0,
            'allow_register': 1,
            'default_register_type': 'phone',
            'activation_required': 0
        }

        # 应用默认配置
        results = {}
        for key, value in default_configs.items():
            success = set_config(key, value, admin_id=admin_id)
            results[key] = success

        return jsonify({
            'code': 0,
            'message': '重置配置成功',
            'data': results
        })
    except Exception as e:
        current_app.logger.error(f"重置配置失败: {str(e)}")
        return jsonify({
            'code': 1,
            'message': f'重置配置失败: {str(e)}'
        }), 500


@admin_blueprint.route('/card/record', methods=['POST', 'OPTIONS'])
@admin_required
def create_card_record():
    data = request.json
    user_id = data.get('user_id')
    count = data.get('count')
    remark = data.get('remark', '')

    if not user_id or not count or count <= 0:
        return jsonify({'code': 400, 'msg': '参数不合法'})

    user = Agent.query.filter_by(user_id=user_id).first()
    if not user:
        return jsonify({'code': 404, 'msg': '用户不存在'})

    # 记录开卡日志
    record = CardRecord(
        user_id=user.id,
        admin_id=1,
        count=count,
        remark=remark
    )
    db.session.add(record)

    # 增加用户可生成卡次数
    user.max_generation_count = (user.max_generation_count or 0) + count

    db.session.commit()

    return jsonify({'code': 0, 'msg': '开卡成功'})
